/**
 * 
 */
package com.ai.dmc.index.base.logservice;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.utils.json.JsonUtil;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;


/**
 * Title： 
 * Description： 
 * Copyright：Copyright (c) 2009
 * Company：北京亚信智慧数据科技有限公司
 * @author xc, Mar 21, 2016
 * @version 1.0
 */
public class LogService extends BaseServiceImpl{
    private Map<String,Logger> logMap = new HashMap<String, Logger>();
    private Logger getLogger(String loggerName){
        if(logMap.containsKey(loggerName)){
            return logMap.get(loggerName);
        }else{
            Logger loginst = LoggerFactory.getLogger(loggerName);
            logMap.put(loggerName, loginst);
            return loginst;
        }
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void writerLog(InputObject inputObject, OutputObject outputObject){
        Logger log = LoggerFactory.getLogger("syslog.DATABASE_WEB_VIEW");
        log.info("syslog.DATABASE_WEB_VIEW");
        Logger logss = LoggerFactory.getLogger("syslog.CONSOLE");
        logss.info("syslog.DATABASE_WEB_VIEW");
        Map<String, Class> map = new HashMap<String, Class>();
        map.put("message", Map.class);
        Map<String, Object> message = JsonUtil.JsonString2Map(inputObject.getParams().get("message"),map);
        Logger logger = getLogger(inputObject.getParams().get("logger"));
        String level = inputObject.getParams().get("level").toLowerCase();
        for(String key:message.keySet()){
            if(!"msg".equals(key)){
                MDC.put(key, (String) message.get(key));
            }
        }
        
        try {
            Class cs = logger.getClass();
            Method md = cs.getMethod(level,String.class);
            md.invoke(logger,message.get("msg"));
        } catch (Exception e) {
            getLogger("").error("Error when invoking method[{}] and will miss log message[{}]",level,inputObject.getParams().get("message"));
        }
    }
}
